from flask import Blueprint, current_app, request, g, send_from_directory
from flask.helpers import send_file
from flask_restful import Api, Resource
from app.utils import download_validate_token, make_res
from app.operation.files import DownloadFile
import os
download_bp = Blueprint('download', __name__)
api = Api(download_bp)

# 用户下载文件接口
class UserDownloadView(Resource):
    def get(self):
        pass

    def post(self):
        ''' 
            通过获取表单中的token做鉴权
            这里的token和报文头中的token一致
        '''
        try:
            token = request.form.get('token', None)
            path = request.form.get('path')
            if token is None or path is None:
                return make_res(message="缺少必要参数")

            if download_validate_token(token):
                # 返回下载文件 
                file = DownloadFile(g.username, path)
                print("token ok")
                file_path = file.get_file()
                print(file_path)
                # filepath = os.path.join(current_app['UPLOAD_FOLDER'], file_path, filename)
                # print(filepath)
                return send_file(filename_or_fp=file_path, as_attachment=True, add_etags=True, conditional=True)
                # return send_from_directory(file_path, filename, as_attachment=True)
            return make_res(code=-1, message='未登录')
        except ValueError as e:
            current_app.logger.info(e)
            return make_res(code=-1, message=str(e))
        except Exception as e:
            current_app.logger.error(e)
            return make_res(code=-9, message=str(e))

# @download_bp.route('/private', methods=['POST'])
# def privateDownloadView():
#     try:
#         token = request.form.get('token', None)
#         path = request.form.get('path')
#         if token is None or path is None:
#             return make_res()
#         if download_validate_token(token):
#             # 返回下载文件 
#             file = DownloadFile(g.username, path)
#             file_path, filename = file.get_file()
#             return send_from_directory(file_path, filename, as_attachment=True)
#             pass
#     except Exception as e:
#         return str(e)


api.add_resource(UserDownloadView, '/private')